package com.example.managemyself.util;

import android.content.Context;
import android.util.Log;
import android.os.Handler;
import android.os.Looper;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 和风天气API工具类
 * 使用HTTP请求直接调用和风天气API
 */
public class QWeatherHelper {
    
    private static final String TAG = "QWeatherHelper";
    
    // 和风天气免费API配置
    private static final String GEO_API_URL = "https://geoapi.qweather.com/v2/city/lookup";
    private static final String WEATHER_API_URL = "https://devapi.qweather.com/v7/weather/now";
    private static final String API_KEY = "your_qweather_key"; // 需要替换为实际的API Key
    
    private static QWeatherHelper instance;
    private OkHttpClient httpClient;
    private ExecutorService executorService;
    private Handler mainHandler;
    
    public static synchronized QWeatherHelper getInstance() {
        if (instance == null) {
            instance = new QWeatherHelper();
        }
        return instance;
    }
    
    private QWeatherHelper() {
        httpClient = new OkHttpClient.Builder()
                .connectTimeout(10, java.util.concurrent.TimeUnit.SECONDS)
                .readTimeout(10, java.util.concurrent.TimeUnit.SECONDS)
                .build();
        executorService = Executors.newFixedThreadPool(3);
        mainHandler = new Handler(Looper.getMainLooper());
    }
    
    /**
     * 初始化和风天气工具类
     */
    public void initialize(Context context) {
        Log.i(TAG, "和风天气工具类初始化完成");
    }
    
    /**
     * 根据城市名称搜索城市信息
     */
    public void searchCity(String cityName, WeatherCallback callback) {
        // 检查线程池状态，如果已关闭则重新创建
        if (executorService.isShutdown() || executorService.isTerminated()) {
            executorService = Executors.newFixedThreadPool(3);
        }
        
        try {
            executorService.execute(() -> {
            try {
                String url = GEO_API_URL + "?location=" + cityName + "&key=" + API_KEY + "&lang=zh";
                Request request = new Request.Builder()
                        .url(url)
                        .get()
                        .build();
                
                Response response = httpClient.newCall(request).execute();
                if (response.isSuccessful() && response.body() != null) {
                    String responseBody = response.body().string();
                    JSONObject jsonObject = new JSONObject(responseBody);
                    
                    if ("200".equals(jsonObject.getString("code"))) {
                        JSONArray locationArray = jsonObject.getJSONArray("location");
                        List<CityInfo> cities = new ArrayList<>();
                        
                        for (int i = 0; i < locationArray.length(); i++) {
                            JSONObject cityObj = locationArray.getJSONObject(i);
                            CityInfo city = new CityInfo();
                            city.id = cityObj.getString("id");
                            city.name = cityObj.getString("name");
                            city.adm1 = cityObj.getString("adm1");
                            city.adm2 = cityObj.getString("adm2");
                            city.lat = cityObj.getString("lat");
                            city.lon = cityObj.getString("lon");
                            cities.add(city);
                        }
                        
                        mainHandler.post(() -> callback.onCitySearchSuccess(cities));
                    } else {
                        mainHandler.post(() -> callback.onError("未找到相关城市"));
                    }
                } else {
                    mainHandler.post(() -> callback.onError("网络请求失败"));
                }
            } catch (IOException | JSONException e) {
                Log.e(TAG, "城市搜索异常", e);
                mainHandler.post(() -> callback.onError("城市搜索异常: " + e.getMessage()));
            }
        });
        } catch (RejectedExecutionException e) {
            Log.e(TAG, "线程池已关闭，城市搜索任务被拒绝", e);
            mainHandler.post(() -> callback.onError("服务暂时不可用，请稍后重试"));
        }
    }
    
    /**
     * 根据经纬度获取当前天气
     */
    public void getCurrentWeatherByLocation(double latitude, double longitude, WeatherCallback callback) {
        String location = latitude + "," + longitude;
        getCurrentWeather(location, callback);
    }
    
    /**
     * 根据城市ID获取当前天气
     */
    public void getCurrentWeatherByLocationId(String locationId, WeatherCallback callback) {
        getCurrentWeather(locationId, callback);
    }
    
    /**
     * 获取当前天气的内部方法
     */
    private void getCurrentWeather(String location, WeatherCallback callback) {
        // 检查线程池状态，如果已关闭则重新创建
        if (executorService.isShutdown() || executorService.isTerminated()) {
            executorService = Executors.newFixedThreadPool(3);
        }
        
        try {
            executorService.execute(() -> {
            try {
                String url = WEATHER_API_URL + "?location=" + location + "&key=" + API_KEY + "&lang=zh";
                Request request = new Request.Builder()
                        .url(url)
                        .get()
                        .build();
                
                Response response = httpClient.newCall(request).execute();
                if (response.isSuccessful() && response.body() != null) {
                    String responseBody = response.body().string();
                    JSONObject jsonObject = new JSONObject(responseBody);
                    
                    if ("200".equals(jsonObject.getString("code"))) {
                        JSONObject nowObj = jsonObject.getJSONObject("now");
                        
                        WeatherInfo weatherInfo = new WeatherInfo();
                        weatherInfo.temperature = nowObj.getString("temp");
                        weatherInfo.weatherText = nowObj.getString("text");
                        weatherInfo.iconCode = nowObj.getString("icon");
                        weatherInfo.windDir = nowObj.getString("windDir");
                        weatherInfo.windSpeed = nowObj.getString("windSpeed");
                        weatherInfo.humidity = nowObj.getString("humidity");
                        weatherInfo.pressure = nowObj.getString("pressure");
                        weatherInfo.visibility = nowObj.getString("vis");
                        weatherInfo.feelsLike = nowObj.getString("feelsLike");
                        weatherInfo.updateTime = jsonObject.getString("updateTime");
                        
                        mainHandler.post(() -> callback.onWeatherSuccess(weatherInfo));
                    } else {
                        mainHandler.post(() -> callback.onError("获取天气信息失败"));
                    }
                } else {
                    mainHandler.post(() -> callback.onError("网络请求失败"));
                }
            } catch (IOException | JSONException e) {
                Log.e(TAG, "天气获取异常", e);
                mainHandler.post(() -> callback.onError("天气获取异常: " + e.getMessage()));
            }
        });
        } catch (RejectedExecutionException e) {
            Log.e(TAG, "线程池已关闭，任务被拒绝", e);
            mainHandler.post(() -> callback.onError("服务暂时不可用，请稍后重试"));
        }
    }
    
    /**
     * 天气信息数据类
     */
    public static class WeatherInfo {
        public String temperature;      // 温度
        public String weatherText;      // 天气描述
        public String iconCode;         // 天气图标代码
        public String windDir;          // 风向
        public String windSpeed;        // 风速
        public String humidity;         // 湿度
        public String pressure;         // 气压
        public String visibility;       // 能见度
        public String feelsLike;        // 体感温度
        public String updateTime;       // 更新时间
        
        @Override
        public String toString() {
            return weatherText + " " + temperature + "°C";
        }
        
        public String getDetailedInfo() {
            return String.format("天气: %s\n温度: %s°C\n体感: %s°C\n湿度: %s%%\n风向: %s\n风速: %s km/h",
                    weatherText, temperature, feelsLike, humidity, windDir, windSpeed);
        }
    }
    
    /**
     * 城市信息数据类
     */
    public static class CityInfo {
        public String id;           // 城市ID
        public String name;         // 城市名称
        public String adm1;         // 省份
        public String adm2;         // 城市上级行政区
        public String lat;          // 纬度
        public String lon;          // 经度
        
        @Override
        public String toString() {
            return name + ", " + adm1;
        }
    }
    
    /**
     * 天气回调接口
     */
    public interface WeatherCallback {
        void onWeatherSuccess(WeatherInfo weatherInfo);
        void onCitySearchSuccess(List<CityInfo> cities);
        void onError(String error);
    }
    
    /**
     * 释放资源 - 谨慎使用，只在应用完全退出时调用
     */
    public void release() {
        if (executorService != null && !executorService.isShutdown()) {
            executorService.shutdown();
            try {
                // 等待任务完成，最多等待5秒
                if (!executorService.awaitTermination(5, java.util.concurrent.TimeUnit.SECONDS)) {
                    executorService.shutdownNow();
                }
            } catch (InterruptedException e) {
                executorService.shutdownNow();
                Thread.currentThread().interrupt();
            }
        }
    }
    
    /**
     * 检查服务是否可用
     */
    public boolean isServiceAvailable() {
        return executorService != null && !executorService.isShutdown() && !executorService.isTerminated();
    }
} 